﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Threading;

namespace AutomateVariations
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("in progress...");

            SPSite site = new SPSite("http://sp2013dev/");
            SPWeb web = site.OpenWeb();
            ConfigureVariationsSettings(web);
            CreateVariations(web);
            CreateHierarchies(site, web);

            Console.WriteLine("DONE");
        }

        private static void ConfigureVariationsSettings(SPWeb rootWeb)
        {
            Guid varRelationshipsListId = new Guid(rootWeb.AllProperties["_VarRelationshipsListId"] as string);
            SPList varRelationshipsList = rootWeb.Lists[varRelationshipsListId];
            SPFolder rootFolder = varRelationshipsList.RootFolder;
            // Automatic creation
            rootFolder.Properties["EnableAutoSpawnPropertyName"] = "true";
            // Recreate Deleted Target Page; set to false to enable recreation
            rootFolder.Properties["AutoSpawnStopAfterDeletePropertyName"] = "false";
            // Update Target Page Web Parts
            rootFolder.Properties["UpdateWebPartsPropertyName"] = "true";
            // Resources
            rootFolder.Properties["CopyResourcesPropertyName"] = "true";
            // Notification
            rootFolder.Properties["SendNotificationEmailPropertyName"] = "false";
            rootFolder.Properties["SourceVarRootWebTemplatePropertyName"] = "CMSPUBLISHING#0";
            rootFolder.Update();

            SPListItem item = null;
            if (varRelationshipsList.Items.Count > 0)
            {
                item = varRelationshipsList.Items[0];
            }
            else
            {
                item = varRelationshipsList.Items.Add();
                item["GroupGuid"] = new Guid("F68A02C8-2DCC-4894-B67D-BBAED5A066F9");
            }

            item["Deleted"] = false;
            item["ObjectID"] = rootWeb.ServerRelativeUrl;
            item["ParentAreaID"] = String.Empty;
            item.Update();
        }

        public class VariationLabel
        {
            public string Title {get;set;}
            public string Description {get; set;}
            public string FlagControlDisplayName {get;set;}

            public string Language {get; set;}

            public uint Locale {get; set;}
            public string HierarchyCreationMode {get; set;}
            public string SourceVarRootWebTemplate {get;set;}
            public bool IsSource{get;set;}
        }

        public static class CreationMode
        {
            public const string PublishingSitesAndAllPages = "Publishing Sites and All Pages";
            public const string PublishingSitesOnly ="Publishing Sites Only";
            public const string RootSitesOnly ="Root Sites Only";
        }

        private static VariationLabel[] labels = {
                                                     new VariationLabel
                                                     {
                                                         Title="ar-sa",
                                                         FlagControlDisplayName="Arabic Egypt",
                                                         Language="ar-SA",
                                                         Locale=1025,
                                                         HierarchyCreationMode=CreationMode.PublishingSitesAndAllPages,
                                                         IsSource=true
                                                     },
                                                     new VariationLabel
                                                     {
                                                         Title ="en-us",
                                                         FlagControlDisplayName="English US",
                                                         Language ="en-US",
                                                         Locale=1033,
                                                         HierarchyCreationMode=CreationMode.PublishingSitesAndAllPages
                                                     }
                                                 };

        private static void CreateVariations(SPWeb rootWeb)
        {
            Guid varListId = new Guid(rootWeb.AllProperties["_VarLabelsListId"] as string);
            SPList varList = rootWeb.Lists[varListId];
            foreach(VariationLabel label in labels)
            {
                SPListItem item = varList.Items.Add();
                item[SPBuiltInFieldId.Title]=label.Title;
                item["Description"] = label.Description;
                item["Flag Control Display Name"]=label.FlagControlDisplayName;
                item["Language"]=label.Language;
                item["Locale"]=label.Locale.ToString();
                item["Hierarchy Creation Mode"]=label.HierarchyCreationMode;
                item["Is Source"]=label.IsSource.ToString();
                item["Hierarchy Is Created"]=false;
                item.Update();
            }
        }

        private static void CreateHierarchies(SPSite site, SPWeb rootWeb)
        {
            site.AddWorkItem(Guid.Empty, DateTime.Now.ToUniversalTime(), 
                new Guid("e7496be8-22a8-45bf-843a-d1bd83aceb25"), 
                rootWeb.ID, site.ID, 1, false, Guid.Empty, Guid.Empty, 
                rootWeb.CurrentUser.ID, null, String.Empty, Guid.Empty, false);
            
            SPWebApplication webApplication = site.WebApplication;
            SPJobDefinition variationsJob = (from SPJobDefinition job in
                                                 webApplication.JobDefinitions
                                             where job.Name == "VariationsCreateHierarchies"
                                             select job).FirstOrDefault();

            if (variationsJob != null)
            {
                DateTime startTime = DateTime.Now.ToUniversalTime();
                variationsJob.RunNow();

                // wait until the job is finished
                while ((from SPJobHistory j in webApplication.JobHistoryEntries 
                        where j.JobDefinitionId == variationsJob.Id && j.StartTime > startTime select j).Any() == false)
                {
                    Thread.Sleep(100);
                }
            }
        }
    }
}
